package com.gy.controller.result;

import com.alibaba.excel.EasyExcel;
import com.gy.controller.common.UserHolder;
import com.gy.entity.Export.CustomCellWriteHandler;
import com.gy.entity.Export.ExportField;
import com.gy.entity.Export.ExportRequest;
import com.gy.entity.result.CopyRight;
import com.gy.query.CopyRightQuery;
import com.gy.result.Result;
import com.gy.service.CopyRightService;
import com.gy.vo.PageVO;
import com.gy.vo.summary.CopyRightVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/copy/right")
@Api(tags = "软件著作权接口")
@CrossOrigin
public class CopyRightController
{
    @Autowired
    private CopyRightService copyRightService;

    /**
     * 根据openid分页查看某个人的软件著作
     */
    @PostMapping("/get/CopyRight")
    @ApiOperation("根据openid查看某个人的软件著作信息")
    public Result<PageVO<CopyRight>> getPapers(@RequestBody CopyRightQuery copyRightQuery){
        return copyRightService.getPapers(copyRightQuery);
    }

    /**
     * 根据id主键删除软件著作权
     */
    @DeleteMapping("/deleteById/{id}")
    @ApiOperation("根据id主键删除软件著作权")
    public Result deleteById(@PathVariable Long id){
        return copyRightService.removeCopyRight(id);
    }

    /**
     * 根据id主键查看某个人的软件著作权
     */
    @GetMapping("/getCopyRightById/{id}")
    @ApiOperation("根据id主键查看某个人的软件著作权")
    public Result getCopyRightById(@PathVariable Long id){
        return Result.success(copyRightService.getCopyRightById(id));
    }

    /**
     * 更改软件著作权
     */
    @PutMapping("/update")
    @ApiOperation("更改软件著作权信息")
    public Result update(@RequestBody CopyRight copyRight){
        return copyRightService.updateCopyRight(copyRight);
    }


    /**
     * 新增软件著作权
     */
    @PostMapping("/save")
    @ApiOperation("新增软件著作权")
    public Result AddPapers(@RequestBody CopyRight copyRight){
        return Result.success(copyRightService.saveCopyRight(copyRight));
    }

    /**
     * 根据多个id查询软件著作
     */
    @PostMapping("/getCopyRightByIds")
    @ApiOperation("通过多个id查询软件著作信息")
    public Result getCopyRightByIds(@RequestBody Long[] ids){
        return copyRightService.getCopyRightByIds(ids);
    }

    /**
     * excel批量导出
     */
    @PostMapping("/export/copyright")
    @ApiOperation("excel批量导出")
    public void exportPapers(@RequestBody ExportRequest request, HttpServletResponse response) throws IOException {
        List<ExportField> fields = request.getFields();
        List<Map<String, Object>> data = request.getData();

        String fileName = "exported_CopyRight.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 动态生成表头
        List<List<String>> head = fields.stream()
                .map(field -> Arrays.asList(field.getLabel()))
                .collect(Collectors.toList());

        // 将 Map<String, Object> 转换为 List<List<Object>>
        List<List<Object>> transformedData = data.stream()
                .map(map -> fields.stream()
                        .map(field -> map.get(field.getKey()))
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());

        // 写入数据
        EasyExcel.write(response.getOutputStream())
                .head(head)
                .registerWriteHandler(new CustomCellWriteHandler(fields))
                .sheet("CopyRight")
                .doWrite(transformedData);
    }

    /**
     * 汇总表格中返回软件著作权信息
     */
    @GetMapping("/getCopyRightsBySummary")
    @ApiOperation("汇总表格中返回软件著作权信息")
    public Result<List<CopyRightVO>> getCopyRightsBySummary() {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("用户登录信息异常");
        }

        // 查询并选择 CopyRightVO 中的字段
        List<CopyRight> list = copyRightService.lambdaQuery()
                .eq(CopyRight::getUserId, userId)
                .select(
                        CopyRight::getTitle,
                        CopyRight::getCertificateNo,
                        CopyRight::getPuttime,
                        CopyRight::getCopyrightType,
                        CopyRight::getCopyrightOwner,
                        CopyRight::getAuthorRank,
                        CopyRight::getFinishTime,
                        CopyRight::getRegisterNo
                )
                .list();

        // 将查询结果转换为 CopyRightVO 列表
        List<CopyRightVO> voList = list.stream()
                .map(copyRight -> CopyRightVO.builder()
                        .title(copyRight.getTitle())
                        .certificateNo(copyRight.getCertificateNo())
                        .puttime(copyRight.getPuttime())
                        .copyrightType(copyRight.getCopyrightType())
                        .copyrightOwner(copyRight.getCopyrightOwner())
                        .authorRank(copyRight.getAuthorRank())
                        .finishTime(copyRight.getFinishTime())
                        .registerNo(copyRight.getRegisterNo())
                        .build())
                .collect(Collectors.toList());

        return Result.success(voList);
    }

}
